<template>
	<view class="bg-white">
		<cu-custom :bgColor="'bg-'+ theme.themeColor" :isBack="false">
			<block slot="content">我的购物车</block>
		</cu-custom>
		<view class="flex justify-between align-center padding-sm bg-white solid-bottom shadow fixed">
			<view>
				共{{shoppingCartList.length}}件宝贝
			</view>
			<view>
				<button class="cu-btn sm" :class="'bg-'+ theme.matchColor"
					@tap="isEdit=!isEdit">{{isEdit?'完成' :'编辑'}}</button>
			</view>
		</view>
		<view style="top: unset !important; margin-top: 90rpx;" class="shopping-cart">
			<checkbox-group @change="checkboxChange">
				<view class="cu-card solid-bottom padding-sm " v-for="(item,index) in shoppingCartList" :key="index">
					<view class="flex align-center">
						<checkbox class="round margin-lr-xs" :class="item.checked? theme.themeColor+' checked':''"
							:disabled="item.goodsSku.stock <= 0 && !isEdit" :checked="item.checked" :value="item.id">
						</checkbox>
						<navigator hover-class="none" style="width:100%" :disabled="item.goodsSku.stock <= 0"
							:url="'/pages/goods/goods-detail/index?id=' + item.spuId">
							<view class="content">
								<view class="flex flex-wrap">
									<view style="width: 30%;height: 102px;position: relative;"
										class="flex align-center justify-center">
										<image :src="item.picUrl" mode="aspectFill" class="margin-top-sm flex-sub"
											style="width: 100%;height: 102px;">
										</image>
										<view v-if="!item.goodsSku || item.goodsSku.stock<=0"
											class="out-stock flex align-center justify-center">
											<text class="text-white">无 货</text>
										</view>
									</view>

									<view class="desc padding-left-sm block flex-twice">
										<text class="hx-overflow-2"
											:class="!item.goodsSku || item.goodsSku.stock<=0 ? 'text-gray': 'text-black'">{{item.spuName}}</text>
										<view class="bg-gray radius text-gray margin-top-xs padding-xs"
											v-if="item.specsInfo && item.goodsSku" @tap.stop="openGoodsSku(item)">
											<text class="text-gray text-sm">{{item.specsInfo}}</text>
											<text class="cuIcon-unfold text-gray"></text>
										</view>
										<view class="flex justify-between padding-top-lg">
											<view class="text-price text-bold text-lg"
												:class="!item.goodsSku || item.goodsSku.stock<=0 ? 'text-gray':'text-'+ theme.themeColor">
												{{item.goodsSku.salesPrice}}
											</view>
											<view @tap.stop>
												<view v-if="!item.goodsSku || item.goodsSku.stock<=0">
													<text class="text-bold text-sm"
														:class="'text-'+theme.themeColor">更多相似</text>
												</view>
												<view v-else>
													<uni-number-box :min="1" :max="999" v-model="item.quantity"
														:disabled="item.quantity == 0 ||  item.quantity>item.goodsSku.stock"
														@change="numberBoxChange(item)">
													</uni-number-box>
												</view>

											</view>
										</view>
									</view>
								</view>

							</view>
						</navigator>
					</view>
				</view>
			</checkbox-group>
			<view v-if="shoppingCartList.length<=0" class="margin-top">
				<view class="margin-top flex justify-center">
					<image style="height:153px;width: 144px;" class="margin-top"
						src="/static/image/default/empty-shopping-cart.png" />
				</view>
				<view class="margin-top flex justify-center">
					<navigator hover-class="none" url="/pages/goods/goods-list/index">
						<button class="cu-btn margin-top" :class="'bg-'+theme.themeColor">去逛逛</button>
					</navigator>
				</view>
			</view>

		</view>

		<view class="cu-bar justify-center  margin-top-sm">
			<view class="action text-bold" :class="'text-'+theme.themeColor">
				<text class="cuIcon-move"></text> <text class="cuIcon-appreciate"></text>为您推荐<text
					class="cuIcon-move"></text>
			</view>
		</view>
		<goods-list :goodsList="goodsSpuList"></goods-list>
		<!-- 底部操作栏 -->
		<view class="cu-bar bg-white padding-sm foot">
			<checkbox-group @change="changeShoppingCartAll">
				<checkbox class="round sm" :class="checkedAll? theme.themeColor+' checked':''" value="selectedAll"
					:checked="checkedAll">
				</checkbox><text class="padding-xs">全选</text>
			</checkbox-group>
			<view v-if="isEdit">
				<button class="cu-btn round" @tap="delGoods">删除</button>
			</view>
			<view class="flex align-center" v-else>
				<view class="padding-xs">合计：<text class="text-price text-lg "
						:class="'text-'+ theme.themeColor">{{totalPrice}}</text></view>
				<button class="cu-btn round shadow-blur" :class="'bg-'+ theme.themeColor" @tap="buySub"
					:disabled="showCreateOrder">结算
					{{selectedValue.length >0 ? '('+selectedValue.length+')':''}}</button>
			</view>
		</view>


		<vk-data-goods-sku-popup v-if="isShow" ref="skuPopup" :shoppingCartId="shoppingCart.id" v-model="skuModal"
			:localdata="goodsSpu" :defaultSelect="selectedSku" skuArrName="goodsSkuSpecsValues" skuListName="goodsSkus"
			specListName="goodsSpuSpecs" @close="skuClose" :mode="modelTpye">
		</vk-data-goods-sku-popup>
	</view>
</template>

<script>
	import {
		getPage as getShoppingCartPage,
		shoppingCartDel
	} from '@/api/shoppingcart.js';
	import {
		getPage as goodsSpuPage,
		getById as goodsSpuById
	} from '@/api/goodsspu.js';
	import GoodsList from "components/goods-list/col-list/index";
	import store from '@/store/index' // store
	export default {
		components: {
			GoodsList
		},
		data() {
			return {
				queryParams: {},
				page: {
					currentPage: 1,
					pageSize: 80,
					descs: 'create_time',
				},
				isLoad: true,
				theme: getApp().globalData.theme,
				shoppingCartList: [],
				selectedValue: [], // 选中数据
				checkedAll: false, //是否全选
				totalPrice: 0,
				shoppingCart: {},
				goodsSpu: null,
				skuModal: false,
				showCreateOrder: true,
				selectedSku: {
					sku: []
				},
				effectiveGoodsIds: 0, //有效商品id
				isShow: false,
				isEdit: false,
				goodsSpuList: [], //推荐商品
				modelTpye: '' //1:都显示  2:只显示购物车 3:只显示立即购买 4:显示缺货按钮 默认 1
			}
		},
		onLoad() {
			this.getGoodsList();

		},
		onShow() {
			getApp().initPage().then(res => {
				this.getPage();
				getApp().setTabBarBadge();
			})
		},
		watch: {
			selectedValue(val) {
				if (this.selectedValue.length > 0) {
					this.showCreateOrder = false;
				} else {
					this.showCreateOrder = true;
				}
			},
			isEdit(val) {
				if (!val) {
					this.shoppingCartList.forEach(item => {
						item.checked = false;
					})
					this.checkedAll = false;
				} else {
					this.checkedAll = false;
					if (this.shoppingCartList.length == this.selectedValue.length) {
						this.checkedAll = true;
					}
				}
			}
		},
		methods: {
			//查询购物车商品列表
			getPage() {
				getShoppingCartPage({
					current: this.page.currentPage,
					size: this.page.pageSize,
					descs: this.page.descs
				}).then(res => {
					res.data.records.forEach(item => {
						item.checked = false;
					})
					this.checkedAll = false;
					this.totalPrice = 0;
					this.shoppingCartList = res.data.records;
					this.effectiveGoodsIds = this.shoppingCartList.filter(item => item.goodsSku && item.goodsSku
							.stock > 0)
						.map(
							item => {
								return item.id
							});
				});
			},
			/**
			 * 购物车数量改变
			 */
			numberBoxChange(e) {
				this.$nextTick(function() {
					this.addCart(e)
				})
			},
			/**
			 * 数量修改
			 */
			addCart(dataObj) {
				let data = {
					id: dataObj.id,
					quantity: dataObj.quantity,
				};
				let that = this;
				uni.$myRequest.shoppingCartEdit(data).then(res => {
					that.getPage();
				})

			},
			// 购物车全选
			changeShoppingCartAll(e) {
				this.checkedAll = !this.checkedAll;
				console.log(JSON.stringify(this.checkedAll));
				this.selectedValue = [];
				if (e.detail.value.length > 0) {
					if (this.isEdit) {
						this.selectedValue = this.shoppingCartList.map(
							item => {
								return item.id
							});
					} else {
						this.selectedValue = this.effectiveGoodsIds;
					}
				}
				this.goodsSum();
			},
			// 计算购物车选中商品金额
			goodsSum() {
				var items = this.shoppingCartList,
					values = this.selectedValue;
				this.checkedAll = false;
				// 不是编辑 只能选择有库存商品计算金额
				if (!this.isEdit) {
					let totalPrice = 0;
					items.forEach(item => {
						item.checked = false;
						if (values.indexOf(item.id) > -1 && item.goodsSku && item.quantity <= item
							.goodsSku.stock) {
							totalPrice = Number(totalPrice) + Number(item.quantity) * Number(item
								.goodsSku.salesPrice);
							item.checked = true;
						}
					})
					this.totalPrice = totalPrice.toFixed(2);
					// 如果可购买商品数量等于已勾选数量 设置全选按钮为true
					if (this.effectiveGoodsIds.length == values
						.length) {
						this.checkedAll = true;
					}
				} else { // 编辑所有商品可以选择
					items.forEach(item => {
						item.checked = false;
						if (values.indexOf(item.id) > -1) {
							item.checked = true;
						}
					})
					if (items.length == values
						.length) {
						this.checkedAll = true;
					}
				}


			},
			//下单
			buySub() {
				if (this.shoppingCartList.length > 50) {
					uni.showToast({
						title: '最多只能为50个宝贝下单',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				let goodsList = []
				this.shoppingCartList.forEach(function(shoppingCart, index) {
					if (shoppingCart.checked && shoppingCart.goodsSku && shoppingCart.goodsSku.enable == '1' &&
						shoppingCart.goodsSpu &&
						shoppingCart.goodsSpu.status == '1' && shoppingCart.quantity <= shoppingCart.goodsSku.stock
					) {
						let param = {
							spuId: shoppingCart.spuId,
							skuId: shoppingCart.skuId,
							quantity: shoppingCart.quantity,
							salesPrice: shoppingCart.goodsSku.salesPrice,
							spuName: shoppingCart.goodsSpu.name,
							specsInfo: shoppingCart.specsInfo,
							picUrl: shoppingCart.picUrl ? shoppingCart.picUrl : shoppingCart
								.goodsSpu.spuUrls[0],
							freightTemplate: shoppingCart.goodsSpu.freightTemplate
						};
						goodsList.push(param);
					}
				});
				store.commit('SET_GOODS_LIST', goodsList);
				uni.navigateTo({
					url: '/pages/order/order-confirm/index',
				});
			},
			/**
			 * 打开sku
			 */
			openGoodsSku(row) {
				this.isShow = false;
				this.shoppingCart = row;
				this.getSpu(row.spuId);
				let sku = [];
				row.goodsSku.goodsSkuSpecsValues.forEach(item => {
					sku.push(item.specsValueId);
				})
				this.selectedSku.sku = sku;
				this.selectedSku.num = row.quantity;
				this.selectedSku.specsInfo = row.specsInfo;
				this.modelTpye = 2;
				this.skuModal = true;

			},
			// 查询商品信息
			getSpu(id) {
				goodsSpuById(id).then(res => {
					this.goodsSpu = res.data;
					this.isShow = true;
				});
			},
			// 删除商品
			delGoods() {
				if (this.selectedValue.length > 0) {
					shoppingCartDel(this.selectedValue).then(res => {
						this.getPage();
					})
				}
			},
			checkboxChange(e) {
				this.selectedValue = e.detail.value;
				this.goodsSum();
			},
			// 查询推荐商品列表
			getGoodsList() {
				goodsSpuPage({
					current: 1,
					size: 10,
					descs: 'sales_volume'
				}).then(res => {
					this.goodsSpuList = res.data.records;
				});
			},
			skuClose(data) {
				this.getPage();

			},
		}
	}
</script>

<style lang="scss">
	.shopping-cart {
		position: relative;
	}

	.out-stock {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.8);
	}

	.cu-card-before::before {
		background-color: #F2F3F5;
		opacity: 0.3;
		position: absolute;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		content: "";
		z-index: 1
	}
</style>
